package com.htjx.mall.controllers.commonapi;

import java.util.concurrent.TimeUnit;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.util.WebUtils;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.RemovalListener;
import com.google.common.cache.RemovalNotification;
import com.htjx.mall.commons.models.User;
import com.htjx.mall.commons.utils.MD5;

/**
 * 授权的用户列表
 * 
 * @author jingrenlang
 * 
 */
public class AuthorizeList {
	private static final Logger logger = LoggerFactory.getLogger(AuthorizeList.class);

	private static Cache<String, Long> CACHE = CacheBuilder.newBuilder()
			// 设置失效时间，创建时间
			.expireAfterWrite(6, TimeUnit.HOURS)
			// 设置时效时间，最后一次被访问
			.expireAfterAccess(6, TimeUnit.HOURS)
			// 移除缓存的监听器
			.removalListener(new RemovalListener<String, Long>() {
				public void onRemoval(RemovalNotification<String, Long> notification) {
					String key = notification.getKey();
					long value = notification.getValue();
					logger.info("用户{}过期被销毁，token：{}", value, key);
				}
			}).build();

	public static void set(String key, long value) {
		CACHE.put(key, Long.valueOf(value));
	}

	public static long get(String key) {
		Long value = CACHE.getIfPresent(key);
		return value == null ? 0 : value;
	}

	/**
	 * 先从Cookie中获取token,没有再尝试从request param中获取token
	 */
	public static long getCurrentAuthUser(HttpServletRequest request) {
		Cookie cookie = WebUtils.getCookie(request, Constant.TOKEN_NAME);
		if (cookie == null || StringUtils.isBlank(cookie.getValue())) {
			String token = request.getParameter(Constant.TOKEN_NAME);
			if (StringUtils.isNoneBlank(token)) {
				return AuthorizeList.get(cookie.getValue());
			}
			return 0;
		}
		return AuthorizeList.get(cookie.getValue());
	}
	
	/**
	 * 先从Cookie中获取token,没有再尝试从request param中获取token
	 */
	public static String setCurrentAuthUser(User user, HttpServletResponse response) {
		String token = String.format("%s.%s", user.getId(), System.currentTimeMillis());
		token = MD5.digest(token);
		Cookie cookie = new Cookie("token", token);
		cookie.setMaxAge(5400);
		cookie.setPath("/");
		response.addCookie(cookie);
		
		AuthorizeList.set(token, user.getId());
		
		return token;
	}
}
